package com.edu.zju.scs.panacea.service.plan;

import com.edu.zju.scs.panacea.entity.BaseResult;
import com.edu.zju.scs.panacea.entity.plan.Seller;
import com.edu.zju.scs.panacea.entity.resource.Site;
import com.edu.zju.scs.panacea.mapper.plan.SellerMapper;
import com.edu.zju.scs.panacea.mapper.resource.SiteMapper;
import com.edu.zju.scs.panacea.utils.MathUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;

/**
 * @Author: Yue Liang
 * @Date: 2018-12-12 18:49
 */
@Service
public class SellerService {

    @Autowired
    private SellerMapper sellerMapper;

    public BaseResult getSeller(Long id) {
        BaseResult baseResult = new BaseResult();
        Seller seller = sellerMapper.selectSeller(id);
        if (seller == null) {
            baseResult.error("无此id对应的商家");
        } else {
            baseResult.success(seller);
        }
        return baseResult;
    }

    public BaseResult getAllSeller() {
        BaseResult baseResult = new BaseResult();
        baseResult.success(sellerMapper.selectAllSeller());
        return baseResult;
    }

    public BaseResult deleteSeller(Long id) {
        BaseResult baseResult = new BaseResult();
        long deleteNums = sellerMapper.deleteSeller(id);
        if (deleteNums == 0) {
            baseResult.error("删除失败！");
        } else {
            baseResult.success(deleteNums);
        }
        return baseResult;
    }

    public BaseResult addSeller(Seller seller) {
        BaseResult baseResult = new BaseResult();
        setInitialPassword(seller);
        Long sellerId = sellerMapper.insertSeller(seller);
        if (sellerId == null) {
            baseResult.error("新增商家失败！");
        } else {
            baseResult.success(sellerId);
        }
        return baseResult;
    }

    public BaseResult editSeller(Seller seller) {
        BaseResult baseResult = new BaseResult();
        Long sellerId = sellerMapper.updateSeller(seller);
        if (sellerId == null) {
            baseResult.error("更新商家失败！");
        } else {
            baseResult.success(sellerId);
        }
        return baseResult;
    }

    public BaseResult isValidSeller(String name, String password, HttpSession session) {
        Seller seller = sellerMapper.selectValidSeller(name, password);
        BaseResult baseResult = new BaseResult();
        if (seller == null) {
            baseResult.error("用户名或密码错误");
        }
        else {
            baseResult.success(seller);
            session.setAttribute("seller", seller);
        }
        return baseResult;
    }

    private void setInitialPassword(Seller seller) {
        seller.setPassword(MathUtil.RandomSixBit().toString());
    }
}
